package controllers

import (
	"fmt"
	"os/exec"
	"videoconferencing/server/models"

	"github.com/asdine/storm"
	"github.com/asdine/storm/q"
	"github.com/astaxie/beego"
)

var DB *storm.DB

type BaseController struct {
	beego.Controller
}

type MainController struct {
	BaseController
}

func (c *MainController) Get() {
	c.TplName = "index.html"
}

func (c *MainController) A更新() {
	cmd := exec.Command("git", "pull")
	err := cmd.Run()
	if err != nil {
		c.Fail(1, err)
		return
	}
	c.Success("更新成功")
}

func (c *BaseController) Fail(code int, data interface{}) {
	var msg string
	switch data.(type) {
	case string:
		msg = data.(string)
	default:
		msg = fmt.Sprint(data)
	}
	c.Data["json"] = map[string]interface{}{"code": code, "data": msg}
	c.ServeJSON()
}

func (c *BaseController) Success(data interface{}) {
	c.Data["json"] = map[string]interface{}{"code": 0, "data": data}
	c.ServeJSON()
}

func (c *BaseController) GetUser() (user models.M用户) {
	Token := c.GetString("Token")
	if Token != "" {
		err := DB.Select(q.Eq("Token", Token)).First(&user)
		if err != nil {
			beego.Info("GetUser", err)
		}
	}
	return user
}
